package com.minis.beans;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleBeanFactory implements BeanFactory{
    private List<BeanDefinition> beanDefinitions = new ArrayList<>();
    private List<String> beanNames = new ArrayList<>();
    private Map<String,Object> singletons = new HashMap<>();
    public SimpleBeanFactory(){}

    /**
     * getBean,容器的核心方法
     * @param beanName
     * @return
     * @throws BeanException
     */
    @Override
    public Object getBean(String beanName) throws BeanException {
        // 先尝试直接拿bean
        Object singleton = singletons.get(beanName);
        // 如果此时还没有这个bean实例，则获取他的定义来创建实例
        if (singleton == null){
            int i = beanNames.indexOf(beanName);
            if (i==-1){
                throw new BeanException("no such bean");
            }else{
                BeanDefinition beanDefinition = beanDefinitions.get(i);
                try {
                    singleton = Class.forName(beanDefinition.getClassName()).newInstance();
                    singletons.put(beanDefinition.getId(),singleton);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }

            }

        }
        return singleton;
    }

    @Override
    public void registerBeanDefinition(BeanDefinition beanDefinition) {
        this.beanDefinitions.add(beanDefinition);
        this.beanNames.add(beanDefinition.getId());
    }
}
